<template>
    <div class="inline-video" :id="detail.identifier + '_inline_video'">
        <el-image
            v-if="editMode"
            :style="{
                width: this.detail.style.position.w + 'px',
                height: this.detail.style.position.h + 'px',
            }"
            :src="require('@/assets/images/video-cover.png')"
            @dragstart.prevent
            @dragover.prevent
            @drop.prevent
        ></el-image>
        <div class="video-wrap" v-else>
            <el-tabs class="tab-wrap" v-if="channelList.length !== 0" v-model="tabActive" type="card" @tab-click="handleTabClick">
                <el-tab-pane v-for="(item, index) in channelList" :key="index" :label="item.channelName" :name="item.channelName">
                    <div
                        :style="{
                            borderBottomRightRadius: detail.style.borderRadius + 'px',
                            borderBottomLeftRadius: detail.style.borderRadius + 'px',
                            opacity: detail.style.opacity,
                            width: detail.style.position.w + 'px',
                            height: detail.style.position.h - 22 + 'px',
                            background: 'rgba(13, 14, 27, 0.7)',
                        }"
                        :ref="`inlineVideo_${index}`"
                    ></div>
                    <span v-if="item.status === 1" class="status" style="color: #ffba00">未激活</span>
                    <span v-if="item.status === 2" class="status" style="color: #ff4949">禁止</span>
                    <span v-if="item.status === 4" class="status" style="color: #909399">离线</span>
                </el-tab-pane>
            </el-tabs>
            <div
                v-else
                class="empty-wrap"
                :style="{
                    borderRadius: detail.style.borderRadius + 'px',
                    opacity: detail.style.opacity,
                }"
            >
                <el-empty :image-size="this.detail.style.position.h / 2" description="该设备 / 场景未绑定摄像头或摄像头不在线"></el-empty>
            </div>
        </div>
    </div>
</template>

<script>
import BaseView from './View';
import { ptzdirection } from '@/api/iot/sipdevice';
import { listRelDeviceOrScene, startPlay, closeStream } from '@/api/iot/channel';

export default {
    name: 'ViewInlineVideo',
    extends: BaseView,
    props: {},
    data() {
        return {
            channelList: [],
            tabActive: '',
            jessibucaList: [],
        };
    },
    computed: {},
    mounted() {
        if (!this.editMode) {
            this.getVideoChannelList();
        }
    },
    methods: {
        initVideo() {
            this.channelList.forEach((item, index) => {
                this.jessibucaList[index] = this.initJessibuca(index);
            });
        },
        initJessibuca(index) {
            let isWebGPU = false;
            // 检测webGPU
            if ('gpu' in navigator) {
                isWebGPU = true;
                console.log('支持webGPU');
            } else {
                isWebGPU = false;
                console.log('暂不支持webGPU，降级到webgl渲染');
            }
            // 生成操作按钮
            const operateBtns = {
                fullscreen: true,
                zoom: true,
                ptz: true,
                play: true,
            };
            const jessibuca = new window.JessibucaPro({
                container: this.$refs[`inlineVideo_${index}`][0],
                decoder: '/js/jessibuca-pro/decoder-pro.js',
                videoBuffer: Number(0.2), // 缓存时长
                isResize: false,
                useWCS: false,
                useMSE: false,
                useSIMD: true,
                wcsUseVideoRender: false,
                loadingText: '加载中',
                debug: false,
                showBandwidth: true, // 显示网速
                showPlaybackOperate: true,
                operateBtns: operateBtns,
                forceNoOffscreen: true,
                isNotMute: false,
                showPerformance: false,
                playbackForwardMaxRateDecodeIFrame: 4,
                useWebGPU: isWebGPU, // 使用WebGPU
            });
            this.onCallback(jessibuca, index);
            return jessibuca;
        },
        onCallback(jessibuca, index) {
            jessibuca.on('error', (err) => {
                console.log('jessibuca error', err);
                this.destroy(jessibuca, index);
            });
            jessibuca.on('pause', (pause) => {
                console.log('jessibuca pause', pause);
            });
            jessibuca.on('stats', (stats) => {
                console.log('jessibuca stats', stats);
            });
            jessibuca.on('timeout', function () {
                console.log('jessibuca timeout');
            });
            jessibuca.on('playbackPreRateChange', (rate) => {
                jessibuca.forward(rate);
            });
            let pre = 0;
            let cur = 0;
            jessibuca.on('timeUpdate', function (ts) {
                cur = parseInt(ts / 60000);
                if (pre !== cur) {
                    pre++;
                }
            });
            jessibuca.on(JessibucaPro.EVENTS.ptz, (arrow) => {
                console.log('jessibuca ptz arrow', arrow);
                this.handlePtz(arrow, index);
            });
        },
        destroy(jessibuca, index) {
            if (jessibuca) {
                jessibuca.destroy().then(() => {
                    this.initJessibuca(index);
                });
            }
        },
        handlePtz(arrow, index) {
            let leftRight = 0;
            let upDown = 0;
            if (arrow === 'left') {
                leftRight = 2;
            } else if (arrow === 'right') {
                leftRight = 1;
            } else if (arrow === 'up') {
                upDown = 1;
            } else if (arrow === 'down') {
                upDown = 2;
            }
            var data = {
                leftRight: leftRight,
                upDown: upDown,
                moveSpeed: 125,
            };
            const { deviceSipId, channelSipId } = this.channelList[index];
            if (deviceSipId && channelSipId) {
                ptzdirection(deviceSipId, channelSipId, data).then((res) => {});
            }
        },
        // 获取设备通道
        getVideoChannelList() {
            const { type, serialNumber, sceneModelId } = this.$route.query;
            let serialNum = null;
            let sceneId = null;
            if (Number(type) === 1) {
                serialNum = serialNumber;
            } else if (Number(type) === 2) {
                sceneId = sceneModelId;
            } else {
                serialNum = this.detail.dataBind.serialNumber;
            }
            const params = {
                serialNumber: serialNum,
                sceneModelId: sceneId,
            };
            listRelDeviceOrScene(params).then((res) => {
                if (res.code === 200) {
                    this.$nextTick(() => {
                        this.channelList = res.data;
                        this.tabActive = this.channelList.length !== 0 && this.channelList[0].channelName;
                    });
                    // 等待数据加载
                    setTimeout(() => {
                        if (this.channelList.length !== 0) {
                            this.initVideo();
                            this.handleTabClick({ index: 0 });
                        }
                    }, 100);
                }
            });
        },
        handlePlay(option) {
            if (option.status === 3) {
                startPlay(option.deviceSipId, option.channelSipId).then((res) => {
                    if (res.code === 200) {
                        const playurl = res.data.playurl;
                        this.channelList[option.index].streamId = res.data.streamId;
                        this.channelList[option.index].playurl = res.data.playurl;
                        this.jessibucaList[option.index].play(playurl);
                    }
                });
            }
        },
        // tab 切换
        handleTabClick(tab, event) {
            const index = tab.index;
            let option = this.channelList[index];
            option = { ...option, index };
            this.handlePlay(option);
        },
        // 关闭播放器
        handleCloseJessibuca() {
            this.channelList.forEach((item, index) => {
                if (item.streamId) {
                    closeStream(item.deviceSipId, item.channelId, item.streamId).then((res) => {});
                }
                this.jessibucaList[index].close();
            });
        },
    },
    destroyed() {
        this.handleCloseJessibuca();
    },
};
</script>

<style lang="scss" scoped>
.inline-video {
    width: 100%;
    height: 100%;

    .video-wrap {
        width: 100%;
        height: 100%;

        .tab-wrap {
            ::v-deep .el-tabs__header {
                margin: 0;

                .el-tabs__item {
                    display: table-cell;
                    padding: 0 10px;
                    height: 20px;
                    line-height: 20px;
                    font-size: 10px;
                    font-weight: normal;
                }
            }

            .play-btn {
                position: absolute;
                bottom: 5px;
                left: 5px;
                border-radius: 50%;
                background: #fff;
                padding: 5px;
                cursor: pointer;
                color: #606266;
            }

            .status {
                position: absolute;
                top: 6px;
                left: 8px;
                font-size: 10px;
            }
        }

        .empty-wrap {
            width: 100%;
            height: 100%;
            background: #fff;
        }
    }
}
</style>
